import { Col, Form, Input, Modal, Row, Button, Switch } from 'antd';
import React, { Component } from 'react';
import { isEmpty, isFunction } from 'lodash';
import { connect } from 'dva';
import { createDetail, createForm } from '/common/components/HocCRUD';
import { modelName } from '../config';
import ModalItem from '/common/components/ModalItem';
import ObjectListBox from '/common/componentsTpl/ObjectListBox';
import { maskRgbaStyle } from '@/globalConfig';
import {appConfig} from '@/appConfig';
import ObjectBox from '/common/componentsTpl/ObjectBox';

@Form.create()
@createForm()
class DetailForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 60,
      btnText: '获取验证码',
      capBtnVisible: false,
    };
  }

  getAjaxData() {
    const { compData = {} } = this.props;
    return new Promise((resolve, reject) => {
      this.props.form.validateFieldsAndScroll(async (errors, fieldsValue) => {
        if (isEmpty(errors)) {
          const values = {
            ...fieldsValue,
          };
          compData.id > 0 && (values.id = compData.id);
          resolve(values);
        } else {
          reject(errors);
        }
      });
    });
  }

  captchaInterval() {
    this.setState({
      capBtnVisible: true,
    });
    let interval = window.setInterval(() => {
      if (interval) {
        let tempCount = this.state.count;
        if (1 == tempCount) {
          this.setState({
            capBtnVisible: false,
            count: 60,
            btnText: '获取验证码',
          });
          interval = null;
        } else {
          --tempCount;
          this.setState({
            count: tempCount,
            btnText: `${tempCount} 重新获取`,
          });
        }
      }
    }, 1000);
  }

  onGetCaptcha() {
    const { form } = this.props;
    let $this = this;
    new Promise((resolve, reject) => {
      form.validateFields(['phone'], {}, (err, values) => {
        if (err) {
          reject(err);
        } else {
          $this.captchaInterval();
        }
      });
    });
  }

  render() {
    const { compData } = this.props;
    const { capBtnVisible, btnText } = this.state;
    let formFields = [
      {
        label: '用户姓名',
        fieldName: 'name',
        options: {
          initialValue: compData.name,
          rules: [{
            required: true,
            message: '请输入用户名称',
          }],
        },
        comp: <Input placeholder={`请输入用户名称`}/>,
      },
      {
        label: '员工类型',
        fieldName: 'type',
        options: {
          initialValue: compData.type||null,
          rules: [{
            // required: true,
            message: '请选择员工类型',
            required: true,
          }],
        },
        comp: <ObjectBox appCode={appConfig.EMPLOYEE_CATEGORY.finderCode}/>,
        // nativeProps={{ placeholder: `请选择员工类型`, mode: 'tags' }}
      },
      {
        label: '角色权限',
        fieldName: 'roles',
        options: {
          initialValue: compData.roles,
          rules: [{
            required: true,
            message: '请选择角色权限',
            type: 'array',
          }],
        },
        comp: <ObjectListBox appCode={appConfig.ROLE.finderCode}
                             nativeProps={{ placeholder: `请选择角色权限`, mode: 'tags' }}/>,
      },
      // {
      //   title: '角色权限',
      //   dataIndex: 'roles',
      //   key: 'roles',
      //   render: (text, record) => {
      //     return (
      //       record.roles ? (
      //         map(record.roles, (o, k) => {
      //           return (
      //             <Tag key={`role_${o.id}_${k}`} color="cyan">{o.name}</Tag>
      //           );
      //         })
      //       ) : ''
      //     );
      //   },
      // },
      {
        label: '所属部门',
        fieldName: 'dept',
        options: {
          initialValue: compData.dept || null,
          rules: [{
            required: true,
            message: '请选择所属部门',
          }],
        },
        comp: <ObjectBox appCode={appConfig.DEPARTMENT.finderCode}/>,
      },
      {
        label: '用户手机号',
        fieldName: 'phone',
        options: {
          initialValue: compData.phone,
          rules: [{ required: false, message: '请输入用户手机号' },
            { pattern: /^1\d{10}$/, message: '请输入正确的手机号' }],
        },
        comp: <Input placeholder={`请输入用户手机号`}/>,
      },
      {
        label: '技术负责人',
        fieldName: 'leader',
        options: {
          initialValue: compData.leader,
          valuePropName:'checked',
          rules: [],
        },
        comp: <Switch checkedChildren="是" unCheckedChildren="否"/>,
      }
      // {
      //   //
      //   label: '开启状态',
      //   fieldName: 'enabled',
      //   options: {
      //     initialValue: compData.enabled,
      //     rules: [],
      //   },
      //   comp:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked={compData.enabled}/>,
      // }
    ];

if(compData.id > 0) {
  const arr = [{
    label: '登录账号',
    fieldName: 'code',
    options: {
      initialValue: compData.code,
      rules: [{
        required: true,
        message: '请输入登录账号',
      }],
    },
    comp: <Input disabled={true} placeholder={`请输入登录账号`}/>,
  }];

  // formFields = arr.concat(formFields);
  formFields= [...arr,...formFields]
} else {
  const arr = [{
    label: '登录账号',
    fieldName: 'code',
    options: {
      initialValue: compData.code,
      rules: [{
        required: true,
        message: '请输入登录账号',
      }],
    },
    comp: <Input placeholder={`请输入登录账号`}/>,
  },
  {
    label: '登录密码',
    fieldName: 'password',
    options: {
      initialValue: compData.password,
      rules: [{
        required: true,
        message: '请输入登录密码',
      }],
    },
    comp: <Input placeholder={`请输入登录密码`}/>,
  }];

  // formFields = arr.concat(formFields);

      formFields= [...arr,...formFields]
}
// console.log('compData===========>',compData,compData.enabled)
    // formFields.push({
    //   label: '技术负责人',
    //   fieldName: 'leader',
    //   options: {
    //     initialValue: compData.leader,
    //     rules: [],
    //   },
    //   comp: <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={compData.leader}/>,
    // });
    //保证开启状态排到最后
    formFields.push({
      label: '开启状态',
      fieldName: 'enabled',
      options: {
        initialValue: compData.enabled,
        valuePropName:'checked',
        rules: [],
      },
      comp: <Switch checkedChildren="开" unCheckedChildren="关"/>,
    });


    return (
      <Form layout="horizontal">
        <Row gutter={16}>
          {this.props.getFields(formFields)}
        </Row>
      </Form>
    );
  }
}

@connect(({ loading, employee: { detail, isShowDetail }, global }) => ({
  detail,
  isShowDetail,
  loading,
  global,
}))
@createDetail({ modelName })
class AdminDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.itemRef = React.createRef();
  }

  async handleOk() {
    // console.log('this.itemRef', this.itemRef);
    const {
      saveDetail,
    } = this.props;
    const itemRef = this.itemRef.current;

    if (itemRef && isFunction(itemRef.getAjaxData)) {
      try {
        const values = await itemRef.getAjaxData();
        console.info('get ajaxData values', values);
        Modal.confirm({
          title: '确认保存信息吗?',
          mask:window.confirmRgba,
          centered: true,
          onOk() {
            saveDetail(values);
          },
        });
      } catch (e) {
        // console.log(e);
      }

    } else {
      console.error('AdminDetail Have not getAjaxData function');
    }
  };

  handleCancel(e) {
    this.props.hideDetail();
  }

  render() {
    const { match, id, loading } = this.props;
    const isEdit = (match && match.params.id > 0) || id > 0;
    return (
      <ModalItem
        width={888}
        title={`${isEdit > 0 ? '编辑' : '新建'}员工`}
        visible={this.props.isShowDetail}
        loading={!!loading.models[modelName]}
        onOk={this.handleOk.bind(this)}
        onCancel={this.handleCancel.bind(this)}
      >
        <DetailForm compData={this.props.detail}
                    dispatch={this.props.dispatch}
                    fromLineLeg={8}
                    global={this.props.global}
                    wrappedComponentRef={this.itemRef}/>
      </ModalItem>
    );
  }
}

AdminDetail.propTypes = {};

export default AdminDetail;
